<?php


namespace app\api\controller\Free;


use app\api\controller\AppController;
use app\api\model\Free\FreeGoodsModel;
use app\api\model\Free\FreeOrderModel;
use app\api\model\User\UserAddressModel;
use app\api\model\User\UserLevelModel;
use app\api\model\User\UserWalletModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use think\facade\Db;

class FreeGoods extends AppController
{
    /**
     * @api {get} /get_free_goods_more 免费商品领取页面
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     *  "data":[{
     *   "list":"免费商品列表",
     *   "is_pull":"是否可领取 0：不可领取 1：可领取",
     *   "address":"收货地址",
     *   "order":"用户领取后订单信息"
     * }]
     * @apiVersion 1.0.0
     */
    public function getFreeGoodsMore(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $data = [];
        if(empty($user)){
           return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }else{
            $order = FreeOrderModel::getFreeOrderWhere([['uid','=',$user['id']]]);
            if(!empty($order)){
                $order['goods_info'] = json_decode($order['goods_info'],true);
                $data['order'] = $order;
                $data['is_pull'] = 0;
            }
            if(!empty($user['is_renew'])){
                $data['is_pull'] = 0;
            }else{
                $data['is_pull'] = 1;
            }
            $address = UserAddressModel::getUserAddressWhere(['uid' => $user['id'], 'is_default' => 1]);
            if(!empty($address)){
                $data['address'] = $address;
            }
        }
        $list = FreeGoodsModel::getFreeGoodsWhereMore([['is_show','=',1]]);
        foreach ($list as &$item){
            $item['label'] = json_decode($item['label'],true);
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        unset($item);
        $data['list'] = $list;
        return Util::returnJson(self::CODE_SUCCESS,$data);
    }

    /**
     * @api {post} /create_free_order 免费商品领取提交
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} pay_way 支付方式  2:支付宝 3：微信
     * @apiParam {int} address_id 收货地址ID
     * @apiParam {int} goods_id 商品ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiSuccessExample {json} 部分数据
     *  "data":["pay_way":"支付方式","data":"支付信息(拉取支付)"]
     * @apiVersion 1.0.0
     */
    public function createFreeOrder(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($user)){
            return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }else{
            if(!empty($user['is_renew'])){
                return Util::returnJson(self::CODE_ERROR,null,"当前用户不可领取");
            }
            $order = FreeOrderModel::getFreeOrderWhere([['uid','=',$user['id']]]);
            if(!empty($order)){
                return Util::returnJson(self::CODE_ERROR,null,"你已领取过了");
            }
        }
        if (!in_array($param['pay_way'],[2,3])) {
            return Util::returnJson(self::CODE_ERROR,null,"支付类型错误");
        }
        $address = UserAddressModel::getUserAddressWhere(['id'=>$param['address_id']]);
        if(empty($address)){
            return Util::returnJson(self::CODE_ERROR,null,"请选择收获地址");
        }
        if(empty($param['goods_id'])){
            return Util::returnJson(self::CODE_ERROR,null,"商品错误");
        }
        $free_goods = FreeGoodsModel::getFreeGoodsWhere([['id','=',$param['goods_id']]]);
        if(empty($free_goods)){
            return Util::returnJson(self::CODE_ERROR,null,"商品不存在");
        }
        $order_sn = StrUtil::i()->getOrderSn(6);
        $data = [
            'uid'             => $user['id'],
            'order_sn'        => $order_sn,
            'goods_info'      => json_encode($free_goods),
            'total_price'     => $free_goods['postage'],
            'price'           => 0,
            'deduction_price' => 0,
            'postage'         => $free_goods['postage'],
            'username'        => $address['username'],
            'mobile'          => $address['mobile'],
            'address'         => $address['region'].$address['detailed'],
            'pay_way'         => $param['pay_way'],
            'status'          => 0,
            'up_time'         => date("Y-m-d H:i:s",time()),
            'add_time'        => date("Y-m-d H:i:s",time()),
            'pay_num'         => 1
        ];
        Db::startTrans();
        try {
            $id = FreeOrderModel::addFreeOrder($data);
            if($id){
                //支付


                $result = [];
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,$result,"下单成功");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"领取失败2");
            }
        }catch (\Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"领取失败1");
        }
    }

    /**
     * @api {post} /get_vip_integral 领取开通会员积分
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} level_id 等级ID 默认 2 (只有年会员了)
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVipIntegral(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(empty($user)){
            return Util::returnJson(self::CODE_LOGIN,null,"请登录");
        }else{
            //判断积分已经领取过了
            $log = Db::name('user_integral_bill')->where([['uid','=',$user['id']],['bill_type','=',1],['bill_use_type','=',StrUtil::INTEGRAL_BILL_USE_TYPE['BUY_VIP']]])->find();
            if(!empty($log)){
                return Util::returnJson(self::CODE_ERROR,null,"你已领取过了");
            }
        }
        if(empty($param['level_id'])){
            return Util::returnJson(self::CODE_ERROR,null,"会员信息错误");
        }
        $level = UserLevelModel::getUserLevelWhere([['id','=',$param['level_id']]]);
        if(empty($level)){
            return Util::returnJson(self::CODE_ERROR,null,"会员信息错误");
        }
        if(empty($level['integral'])){
            return Util::returnJson(self::CODE_ERROR,null,"积分设置错误");
        }
        $flag = UserWalletModel::integralIn($user['id'],$level['integral'],StrUtil::INTEGRAL_BILL_USE_TYPE['BUY_VIP'],"开通会员领取积分");
        if($flag){
            return Util::returnJson(self::CODE_SUCCESS,null,"领取成功");
        }else{
            return Util::returnJson(self::CODE_ERROR,null,"领取失败");
        }
    }

}